package com.atguigu.singleton.type6;

/**
 * @ClassName SingleTon05
 * @Description 单例模式-双重检查
 * @Author HongJian-Yang
 * @Date 2020/6/16 23:07
 * @Version 1.0
 */
public class SingleTon06 {
    public static void main(String[] args) {
        SingleTon instance = SingleTon.getInstance();
        System.out.println(instance == SingleTon.getInstance());
    }
}

class SingleTon {
    // 使用volatile,立即更新变量到主存
    private static volatile SingleTon instance;

    private SingleTon() {

    }

    // 先判断是否为空, 再次判断是否为空,双重检查
    public static SingleTon getInstance() {
        if (instance == null) {
            synchronized (SingleTon.class) {
                if (instance == null) {
                    instance = new SingleTon();
                }
            }
        }
        return instance;
    }
}
